#!/bin/sh /etc/rc.common

START=98

EXTRA_COMMANDS="test auto_update restart_services_now download_all download_china_ip_only download_fake_ip_only download_gfw_list_only"

APP='overthewall'
ip_china='/etc/ipset/china'
ip_fake='/etc/ipset/fake'
domain_gfwlist='/etc/ipset/gfwlist'

test() {
# echo "$1" "$2" "$3"
# [ "$1" -eq "1" ] || [ "$2" -eq "1" ] || [ "$3" -eq "1" ] && \
# 	echo "eq 1"
echo $(($1+$2))
}

download_plain() {
	[ -z "$1" ] || [ -z "$2" ] && {
		echo "Could not get file name or URL."
		return 1
	}
	download_file="/tmp/${1##*/}"
	download_url="$2"
	parameter="$3"
	echo "File        :  $1"
	echo "URL         :  $2"
	rm -f 
	if [ -z "$3" ]; then
		wget -qO - "$download_url" > "$download_file" && download_true="1"
	else
		wget -qO - "$download_url" | eval "$parameter" > "$download_file" && download_true="1"
	fi
	[ "$download_true" = '1' ] || {
		echo "* Failed to download file."
		return 1
	}
	cp -f "$download_file" "$1"
	rm -f "$download_file"
	download_count=$(($download_count+1))
	echo "* File has been updated."
	return 0
}

download_php() {
	[ -z "$1" ] || [ -z "$2" ] && {
		echo "Could not get file name or URL."
		return 1
	}
	download_file="/tmp/${1##*/}"
	download_url="$php_url$2"
	echo "File        :  $1"
	remote_md5=$(wget -O - "${download_url}&md5=true" 2>/dev/null)
	[ -z "$remote_md5" ] && {
		echo "Could not get remote file's MD5."
		return 1
	}
	echo "Remote md5  :  $remote_md5"
	if [ -f "$1" ]; then
		local_md5=$(md5sum "$1" | grep -o '[0-9a-zA-Z]\{32\}')
		[ -z "$local_md5" ] && {
			echo "Could not get local file's MD5."
			return 1
		}
	else
		local_md5="File does not exist."
	fi
	echo "Local md5   :  $local_md5"
	[ "$local_md5" = "$remote_md5" ] || {
		wget -qO "$download_file" "$download_url" && {
			download_md5=$(md5sum "$download_file" | grep -o '[0-9a-zA-Z]\{32\}')
			[ "$download_md5" = "$remote_md5" ] || {
				echo "* Error in download file."
				return 1
			}
			cp -f "$download_file" "$1"
			rm -f "$download_file"
			download_count=$(($download_count+1))
			echo "* File has been updated."
			return 0
		}
		"* Failed to download file."
		return 1
	}
	echo "* File was already up to date."
	return 1
}

download_get_option() {
	config_load "$APP"
	config_get php_url config php_url 'http://leenchan.sourceforge.net/file/index.php'
	download_count='0'
}

download_china_ip() {
	file="/etc/ipset/china"
	config_get chinaip_mode config chinaip_mode '0'
	if [ "$chinaip_mode" = '0' ]; then
		config_get chinaip_plain_url config chinaip_plain_url 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest'
		parameter="awk -F\\| '/CN\\|ipv4/ { printf(\"%s/%d\\n\", \$4, 32-log(\$5)/log(2)) }'"
		download_plain "$file" "$chinaip_plain_url" "$parameter"
	elif [ "$chinaip_mode" = '1' ]; then
		download_php "$file" "?file=delegated-apnic-latest&spuriousip=cn"
	else
		return 1
	fi
}

download_fake_ip() {
	file="/etc/ipset/fake"
	config_get fakeip_mode config fakeip_mode '0'
	if [ "$fakeip_mode" = '0' ]; then
		config_get fakeip_plain_url config fakeip_plain_url 'https://raw.githubusercontent.com/clowwindy/ChinaDNS/master/iplist.txt'
		download_plain "$file" "$fakeip_plain_url"
	elif [ "$fakeip_mode" = '1' ]; then
		download_php "$file" "?file=spurious_ips.conf"
	else
		return 1
	fi
}

download_gfw_list() {
	file="/etc/ipset/gfwlist"
	config_get gfwlist_mode config gfwlist_mode '0'
	if [ "$gfwlist_mode" = '0' ]; then
		config_get fakeip_plain_url config fakeip_plain_url 'http://autoproxy-gfwlist.googlecode.com/svn/trunk/gfwlist.txt'
		parameter="awk -F\\| '/CN\\|ipv4/ { printf(\"%s/%d\\n\", \$4, 32-log(\$5)/log(2)) }'"
		download_plain "$file" "$gfwlist_plain_url"
	elif [ "$gfwlist_mode" = '1' ]; then
		download_php "$file" "?file=gfwlist.txt"
	else
		return 1
	fi
}

download_all() {
	download_get_option
	config_get chinaip_selected config chinaip_selected '0'
	[ "$chinaip_selected" = '1' ] && download_china_ip
	config_get fakeip_selected config fakeip_selected '0'
	[ "$fakeip_selected" = '1' ] && download_fake_ip
	config_get gfwlist_selected config gfwlist_selected '0'
	[ "$gfwlist_selected" = '1' ] && download_gfw_list
}

download_china_ip_only() {
	download_get_option && download_china_ip
}

download_fake_ip_only() {
	download_get_option && download_fake_ip
}

download_gfw_list_only() {
	download_get_option && download_gfw_list
}

auto_update() {
	download_all
	[ "$download_count" -gt 0 ] && restart_services_after_update
}

restart_services() {
	config_get restart_services config restart_services
	[ -z "$restart_services" ] && {
		return 1
	}
	restart_services=$(echo "$restart_services"|tr -d ' '|tr ',' '\n')
	echo -e "$restart_services" | while read LINE
	do
		[ -z "$LINE" ] || {
			if [ "$LINE" = 'shadowsocks' ]; then
				pidof "ss-redir" &>/dev/null && /etc/init.d/shadowsocks restart
			else
				pidof "$LINE" &>/dev/null && /etc/init.d/$LINE restart
			fi
		}
	done
	echo "Services: "$restart_services" restarted."
	return 0
}

restart_services_after_update() {
	config_get restart_enabled config restart_enabled '0'
	[ "$restart_enabled" = '1' ] || {
		return 1
	}
	restart_services
}

restart_services_now() {
	config_load "$APP"
	restart_services
}

cron_get_option() {
	cron_path='/etc/crontabs'
	cron_bin='/etc/init.d/overthewall auto_update'
	if [ -z "$USER" ]; then
		cron_file="$cron_path/root"
	else
		cron_file="$cron_path/$USER"
	fi
}

cron_remove() {
	[ -f "$cron_file" ] && {
		line_no=$(cat "$cron_file" | grep -n -x -m 1 "# $APP" | awk -F':' 'NR=1{print $1}')
		[ -z "$line_no" ] || {
			sed -i "$line_no,$(($line_no+1))d" "$cron_file"
			cron_data=$(cat "$cron_file")
			if [ -z "$cron_data" ]; then
				rm -f "$cron_file"
				/etc/init.d/cron stop
			else
				/etc/init.d/cron restart
			fi
		}
	}
}

cron_set() {
	config_load "$APP"
	config_get auto_update config auto_update '0'
	cron_get_option
	[ "$auto_update" = '0' ] && {
		cron_remove
		return 1
	}
	cron_item="$auto_update $cron_bin"
	[ -d "$cron_path" ] || mkdir -p "$cron_path"
	if [ -f "$cron_file" ]; then
		match_true=$(cat $cron_file | grep -n "$cron_bin")
		if [ -z "$match_true" ]; then
			echo -e "# $APP\n$cron_item" >>"$cron_file"
			/etc/init.d/cron restart
		else
			line_no="${match_true%%:*}"
			cron_item=$(echo -e "$cron_item" | sed 's/\//\\\//g')
			[ -z "$line_no" ] || [ -z "$cron_item" ] || {
				sed -i "${line_no}s/^.*$/$cron_item/" "$cron_file"
				/etc/init.d/cron restart
			}
		fi
	else
		echo -e "# $APP\n$cron_item" >"$cron_file"
		/etc/init.d/cron restart
	fi
}

start() {
	cron_set
}

restart() {
	cron_set
}

stop() {
	cron_get_option
	cron_remove
}
